import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import time
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def add_layer(layoutname,inputs,in_size,out_size,activatuib_funaction=None,):
    with tf.name_scope(layoutname):
        with tf.name_scope('weights'):
            Weights=tf.Variable(tf.random_normal([in_size,out_size]),name='W')
            tf.summary.histogram(layoutname+'/Weights', Weights)
        with tf.name_scope('biases'):
            biases=tf.Variable(tf.zeros([1,out_size])+0.1,name='b')
            tf.summary.histogram(layoutname+'/biases', biases)
        with tf.name_scope('Wx_plus_b'):
            Wx_plus_b=tf.add(tf.matmul(inputs,Weights),biases)

        if activatuib_funaction is None:
            outputs=Wx_plus_b
        else :
            outputs=activatuib_funaction(Wx_plus_b)
        tf.summary.histogram(layoutname+'/outputs', outputs)
        return outputs

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})
    print (tf.argmax(y_pre,1))
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result

xs=tf.placeholder(tf.float32,[None,784])
ys=tf.placeholder(tf.float32,[None,10])

prediction=add_layer('output_layout',xs,784,10,activatuib_funaction=tf.nn.softmax)

cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))

train_step=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())
    t1=time.time()
    for i in range(1000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        t3=time.time()
        sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})
        t4=time.time()

        if i%50==0:
            t5=time.time()
            print(compute_accuracy(
                mnist.test.images, mnist.test.labels))
            t6=time.time()

    t2=time.time()
    print("It took %f seconds" % (t2 - t1))
